//
//  PictureSelectedViewController.swift
//  NSinaWeibo
//
//  Created by LoliQueen on 16/2/26.
//  Copyright © 2016年 LoliQueen. All rights reserved.
//

import UIKit

import HMImagePicker


private let pictureCellID = "pictureCellID"
//设置最大cell个数
private let maxImageCount = 9
///每行最多显示的cell个数
private let cellCount : CGFloat = 4

class PictureSelectedViewController: UICollectionViewController {
    
    ///设置一个图片数组，设置数据源
    lazy var imageList = [UIImage]()
    
    //记录图片数组，记住上次选中的图片
    lazy var selectedAssets = [PHAsset]()


    init(){
        let layout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout: layout)
    
        //设置显示图片的layout
        let w = (ScreenWidth - picMargin*(cellCount + 1)) / cellCount
        layout.itemSize = CGSize(width: w, height: w)
        
        //设置间距
        layout.minimumInteritemSpacing = picMargin
        layout.minimumLineSpacing = picMargin
        //设置组之间的间隙
        layout.sectionInset = UIEdgeInsets(top: picMargin, left: picMargin, bottom: 0, right: picMargin)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置

        //注册cell
        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: pictureCellID)

    }
}


///分类实现数据源方法
extension PictureSelectedViewController{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //如果图片达到最大数量，就
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        ///转化为 pictureCell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureSelectCell
        
        cell.backgroundColor = UIColor.brownColor()

        //设置协议对象
        cell.pictureDelegate = self
        
        
        if imageList.count == indexPath.item{
            //当而这相等时，代表最后一个cell ，设置为空，一遍添加图片
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
        
        
        return cell
    }
}


//遵守协议
extension PictureSelectedViewController: PictureSelectCellDelegate{
    //  实现协议代理方法 .swift中 必须实现这两个方法，不实现会报错
    func userWillChosePicture() {
        print(__FUNCTION__)

//        ///使用系统控件imagePickerController， 调出系统相册
//        let pickerVC = UIImagePickerController()
//        //设置可以编辑图片 设置用户头像，获取正方形图片时会用到
////        pickerVC.allowsEditing = true
//        
//        //如果要对获取的图片信息进行操作，需设置代理，并实现代理方法
//        pickerVC.delegate = self
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        //设置图像选择代理
        picker.pickerDelegate = self
        //设置目标图片的尺寸
        picker.maxPickerCount = 9
        //如果要获取
        //跳转页面
        presentViewController(picker, animated: true, completion: nil)

        ///使用系统控件imagePickerController， 调出系统相册
        let pickerVC = UIImagePickerController()
        //设置可以编辑图片 设置用户头像，获取正方形图片时会用到
//        pickerVC.allowsEditing = true
        
        //如果要对获取的图片信息进行操作，需设置代理，并实现代理方法
        pickerVC.delegate = self
        
        //如果要获取
        //跳转页面
        presentViewController(pickerVC, animated: true, completion: nil)

    }
    
    func userWillDeletePicture(cell: PictureSelectCell) {
        print(__FUNCTION__)
        //确定点击的cell，移除数组中对应的cell
        let indexPath = collectionView?.indexPathForCell(cell)
        imageList.removeAtIndex((indexPath?.item)!)

        //修改记录图片的数组
        selectedAssets.removeAtIndex((indexPath?.item)!)

        //刷新collectionView
        collectionView?.reloadData()
        
    }
    
    
}


//遵守协议，
extension PictureSelectedViewController: HMImagePickerControllerDelegate{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        //记录图像，方便在collectionView 显示
        self.imageList = images
        
        //记录选中资源集合，方便再次选择照片定位
        if selectedAssets != nil{
            self.selectedAssets = selectedAssets!
        }
        //刷新视图
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion:nil)
    }
}

///获取picker的操作，必须遵守两个方法UIImagePickerControllerDelegate，UINavigationControllerDelegate
//extension PictureSelectedViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
//
//    //实现代理方法  已经获取了图片的方法..实现了协议方法，页面的dismiss就交给了程序员
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        //图片信息
//        print(image)
//        //编辑信息
//        print(editingInfo)
//        
//        //把Image添加到 图片数组中
//        imageList.append(image)
//        //刷新
//        collectionView?.reloadData()
//        //手动dismiss
//        dismissViewControllerAnimated(true, completion: nil)
//    }
//}


///获取picker的操作，必须遵守两个方法UIImagePickerControllerDelegate，UINavigationControllerDelegate
extension PictureSelectedViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    //实现代理方法  已经获取了图片的方法..实现了协议方法，页面的dismiss就交给了程序员
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //图片信息
        print(image)
        //编辑信息
        print(editingInfo)
        
        //把Image添加到 图片数组中
        imageList.append(image)
        //刷新
        collectionView?.reloadData()
        //手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}


///定义cell协议，实现添加和删除按钮 的点击事件
//遵守基协议，才能使用weak 修饰代理属性，防止引用循环
protocol PictureSelectCellDelegate : NSObjectProtocol {
    
    func userWillChosePicture()
    func userWillDeletePicture(cell: PictureSelectCell)
}

///自定义cell
class PictureSelectCell : UICollectionViewCell{
    
    //设置代理属性 ,在需要的时候调用代理方法
    weak var pictureDelegate: PictureSelectCellDelegate?
    //设置Image属性，给添加按钮赋值
    var image : UIImage?{
        didSet{
            //当Image为空时，隐藏
            delectBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
       contentView.addSubview(addBtn)
        contentView.addSubview(delectBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(self.snp_center)
            make.edges.equalTo(contentView.snp_edges)
        }
        delectBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        //添加点击事件
        addBtn.addTarget(self, action: "chosePicture", forControlEvents: .TouchUpInside)
        delectBtn.addTarget(self, action: "deletePicture", forControlEvents: .TouchUpInside)
        
        //设置addBtn的图片显示模式 部分缩放填充
        addBtn.imageView?.contentMode = .ScaleAspectFill
    
    }
    
    @objc private func chosePicture(){
        //如果该cell已经有图片就不在添加
        if image != nil{
            print("已经添加了图片")
            return
        }
        pictureDelegate?.userWillChosePicture()
    
    }
    @objc private func  deletePicture(){
        pictureDelegate?.userWillDeletePicture(self)
    
    }
    
    
    //懒加载子控件
    private lazy var addBtn : UIButton = UIButton(backImageName: "compose_pic_add", imageName: nil)
    private lazy var delectBtn : UIButton = UIButton(backImageName: nil, imageName: "compose_photo_close")
    
}
